import React from 'react';
import Utils from '../../utils/utils'
import {fetch, post} from '../../my_axios/api'
import {Card, Button, Table, Icon, Modal, message,Spin} from 'antd';
import Paho from 'paho-mqtt'
import SVG from 'svg.js'
import jquery from 'jquery'

export default class DynamicSvg extends React.Component {
    state = {
        svgHtml:null,
        topicList: [],
        loading:false
    };

    componentWillMount() {
        if( this.props.onRef!==undefined){
            this.props.onRef(this);
        }
        this.getSvgById();
        this.getDiagramFindTags();

    }
    getDiagramFindTags(){
        fetch('diagram/find_tags',{id:this.props.diagramId}).then(res => {
            if (res.status === 'success') {
                let list=[];
                res.data.map((item)=>{
                    list.push(item.topic)
                });
                this.props.subscribeTopic(list)
                this.setState({
                    topicList:list
                });
            } else {
                message.error(res.data.message);
            }
        }).catch(err => {
            console.log(err);
        });
    }

    getSvgById = () => {
        this.setState({
            loading:true
        });
        fetch('diagram/get_svg', {id: this.props.diagramId}).then(res => {
            this.setState({
                svgHtml: res,
                loading:false
            },()=>{
                if(document.getElementById("my_test01").children[0]){
                    let object=document.getElementById("my_test01").children[0];
                    let width = object.getAttribute('width');
                    let height = object.getAttribute('height');
                    var draw = SVG(document.getElementById("my_test01").children[0]).size(this.props.zoomWidth?this.props.zoomWidth:window.innerWidth*0.8,this.props.zoomHeight?this.props.zoomHeight:window.innerHeight*0.7).panZoom({
                        zoomMin: 0.5,
                        zoomMax: 20,
                        zoomFactor: 1,//缩放速率
                    })
                }

            });
        }).catch(err => {
            console.log(err);
            this.setState({
                loading:false
            });
        });
    };
    onMessageArrived(message) {
        let object = {...message};
        let topic = object.destinationName;
        if (object.payloadString && object.payloadString !== ''&&eval("(" + object.payloadString + ")").v!==undefined) {
            let messageObject = eval("(" + object.payloadString + ")");
            if(this.state.topicList.indexOf(topic)!==-1){
                this.updateSVG(messageObject,topic);
            }
        } else {
            console.log("数据格式不对，当前数据：" + object.payloadString)
        }
    }
    // updateSVG=(messageObject,topic)=>{
    //     svg操作
    //     let svgs = SVG.select("[inkscape-label^='idp-tag']").members;
    //     svgs.map((svg) => {
    //         let node = svg.node;
    //         console.log(node.outerHTML.indexOf('{"'));
    //         console.log(node.outerHTML.indexOf('}&quot'));
    //         let newStr=node.outerHTML.substring(node.outerHTML.indexOf('{"'),node.outerHTML.indexOf('}&quot'));
    //         console.log(newStr.replace('\&quot;','1'))
    //         // let list = node.getAttribute('inkscape-label').split(';');
    //     });
    // };
    updateSVG=(messageObject,topic)=>{
        //svg操作
        let svgs = SVG.select("[inkscape-label^='idp-tag']").members;
        svgs.map((svg) => {
            let node = svg.node;
            let list = node.getAttribute('inkscape-label').split(';');
            list.map((listItem) => {
                let objectList = listItem.split('=');
                if (objectList[0].trim() === 'idp-tag-txt') {
                    let object = eval("(" + objectList[1] + ")");
                    if (object.tag === topic) {
                        if(!isNaN(messageObject.v)){
                            node.innerHTML = Utils.changeTwoDecimal_f(messageObject.v);
                        }else{
                            node.innerHTML = messageObject.v;
                        }
                    }
                } else if (objectList[0].trim() === 'idp-tag-bkg') {
                    let object = eval("(" + objectList[1] + ")");
                    if (object.tag === topic) {
                        let configs = object.config;
                        if (configs) {
                            configs.map((config) => {
                                if (messageObject.v >= config.min && messageObject.v <= config.max) {
                                    svg.style("fill", config.color);
                                }
                            })
                        }
                    }

                }
            })
        });
    };
    render() {
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    {
                        this.state.svgHtml!==null? <p id="my_test01" dangerouslySetInnerHTML={{__html: this.state.svgHtml}}/>:null
                    }
                </Spin>
            </div>
        )
    }
}